//
//  YDBTabBarView.swift
//  DKE-Album
//
//  Created by 杨东宝 on 2018/8/2.
//  Copyright © 2018年 杨东宝. All rights reserved.
//

import UIKit

@objc protocol YDBTabBarViewDelegate {
    @objc optional func tabBar(_ tabBar: YDBTabBarView, didClickedButtonAtIndex index: NSInteger)
}

class YDBTabBarView: UIView {
    
    var delegate: YDBTabBarViewDelegate?
    private var buttons: NSMutableArray!
    private var selectedButton: UIButton?

    private lazy var centerButton: YDBTabBarButton = {
        let btn = YDBTabBarButton(type: UIButton.ButtonType.custom)
        btn.setImage(UIImage(named: "icon_menu_add"), for: UIControl.State.normal)
        btn.imageView?.contentMode = UIView.ContentMode.scaleAspectFit
          return btn
      }()
      
    
    var tabBarItems: NSArray! {
        didSet {
            buttons = NSMutableArray.init()
            
            // 遍历模型数组，创建对应tabBarButton
            for i in 0..<tabBarItems.count {
                let btn: YDBTabBarButton = YDBTabBarButton(type: UIButton.ButtonType.custom)
                // 给按钮赋值模型，按钮的内容由模型对应决定
                btn.item = tabBarItems[i] as? UITabBarItem
                // 设置按钮标记
                btn.tag = 10000 + i
                // 为按钮添加事件
                btn.addTarget(self, action: #selector(btnClicked(_:)), for: UIControl.Event.touchUpInside)
                // 初始选中第0个tabBar
                if i == 0 {
                    btnClicked(btn)
                }
                self.addSubview(btn)
                // 把按钮添加到按钮数组
                self.buttons.add(btn)
                
            }
        }
    }
    
    @objc func btnClicked(_ button: YDBTabBarButton) {
        selectedButton?.isSelected = false  // 前一个button
        button.isSelected = true
        selectedButton = button     // 使当前button变成前一个button
        // 响应代理
        delegate?.tabBar!(self, didClickedButtonAtIndex: button.tag - 10000)
    }
    func setSelectIndex(index:Int) {
        self.btnClicked(self.viewWithTag(10000 + index) as! YDBTabBarButton)
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let w: CGFloat = self.bounds.size.width
        let h: CGFloat = kTabBarHeight
        
        var btnX: CGFloat = 0
        let btnY: CGFloat = 0
        let btnW = w / CGFloat(self.buttons.count)
        let btnH = h-kTabbarSafeBottomMargin
        
        // 修改系统tabBar上面的按钮的位置
        for i in 0..<self.buttons.count {
            
            let tabBarButton = self.buttons[i] as! YDBTabBarButton
            btnX = CGFloat(i) * btnW
            tabBarButton.isShowTitle = true
            tabBarButton.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            
        }
    }
}
